package com.linktrip.devicemanager.control.device;

import java.util.concurrent.ExecutionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import com.google.gson.Gson;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.linktrip.devicemanager.entity.DeviceInfo;
import com.linktrip.devicemanager.entity.ResponseText;
import com.linktrip.devicemanager.server.DeviceService;
import com.linktrip.devicemanager.util.CommandUtil;
import com.linktrip.devicemanager.util.ToolKits;
import com.linktrip.devicemanager.websocket.entity.DataStruct;

@Controller
@RequestMapping(value = "/service/test/device")
public class DeviceTestControl {
	Logger logger = LoggerFactory.getLogger(DeviceTestControl.class);

	@Autowired
	private DeviceService server;

	@RequestMapping(value = "/unlock.lt", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String unlock(HttpServletRequest request, HttpServletResponse response) {
		
		String deviceId = ToolKits.getRequestParamValue(request, "deviceid");
		long timestamp = ToolKits.getRequestParamValueForLong(request, "timestamp");
		if (-1L == timestamp)
			timestamp = System.currentTimeMillis();
		ResponseText res = new ResponseText();
		res.setCode(CommandUtil.RESPONSE_ERROR);
		res.setMsg("error");
		Gson gson = new Gson();
		logger.info("deviceId:{}", deviceId);

		DeviceInfo device = server.getDeviceInfoByDeviceNo(deviceId);
		logger.info("device:{}", device == null ? "NULL" : device.toString());
		if (device != null) {
			logger.error("do unlock action.....");
			DataStruct content = CommandUtil.getUnlockCommand(2, 1, 1, timestamp);
			try {
				device = server.unLockDeviceByGPRS(device, content);
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
			if (null == device) {
				res.setCode(CommandUtil.RESPONSE_ERROR);
				res.setMsg("error");
			} else if (device.getStatus() != 2) {
				res.setCode(CommandUtil.RESPONSE_ERROR);
				res.setMsg("error");
			} else if (device.getStatus() == 2) {
				res.setCode(CommandUtil.RESPONSE_OK);
				res.setMsg("SUCCESS");
			}
		}
		return gson.toJson(res);
	}
}
